package com.seadragon.app.ksr.validator;

import static com.seadragon.app.ksr.model.KsrConstants.DEFAULT_MESSAGE_KEY_INVALID_EMAIL;
import static com.seadragon.app.ksr.model.KsrConstants.ERROR_MESSAGE_KEY_FIELD_REQUIRED;
import static com.seadragon.app.ksr.model.KsrConstants.ERROR_MESSAGE_KEY_INVALID_EMAIL;
import static com.seadragon.app.ksr.model.KsrConstants.FIELD_NAME_BUSINESS_NAME;
import static com.seadragon.app.ksr.model.KsrConstants.FIELD_NAME_BUSINESS_TYPE;
import static com.seadragon.app.ksr.model.KsrConstants.FIELD_NAME_EMAIL;
import static com.seadragon.app.ksr.model.KsrConstants.FIELD_NAME_PHONE_NUMBER;
import static com.seadragon.app.ksr.model.KsrConstants.FIELD_NAME_SPECIALTY;

import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.seadragon.app.ksr.model.Business;

public class BusinessValidator implements Validator {
	@Override
	public boolean supports(Class<?> clazz) {
		return Business.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, FIELD_NAME_BUSINESS_NAME, ERROR_MESSAGE_KEY_FIELD_REQUIRED);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, FIELD_NAME_BUSINESS_TYPE, ERROR_MESSAGE_KEY_FIELD_REQUIRED);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, FIELD_NAME_PHONE_NUMBER, ERROR_MESSAGE_KEY_FIELD_REQUIRED);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, FIELD_NAME_SPECIALTY, ERROR_MESSAGE_KEY_FIELD_REQUIRED);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, FIELD_NAME_EMAIL, ERROR_MESSAGE_KEY_FIELD_REQUIRED);
		EmailValidator emailValidator = EmailValidator.getInstance();
		Business business = (Business) target;
		if(business.getEmailAddress() != null && business.getEmailAddress().length() > 0 && !emailValidator.isValid(business.getEmailAddress())){
			errors.rejectValue(FIELD_NAME_EMAIL, ERROR_MESSAGE_KEY_INVALID_EMAIL, DEFAULT_MESSAGE_KEY_INVALID_EMAIL);
		}		
        try {
            errors.pushNestedPath("office");
        } finally {
            errors.popNestedPath();
        }			
	}

}
